﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
//using System.IO.Packaging;
using System.Text;

using Word;

using PowerCreator.LMS.Web.Question;
using PowerCreator.LMS.Question.Entiry;
using PowerCreator.LMS.Web.Course;
using PowerCreator.LMS.Common.Script;
using PowerCreator.LMS.Common.Utils;


public partial class sysadmin_QuestionManager_QuestionToIn : PowerCreator.LMS.Web.Base.BasePage
{
    private string ExcelName_New = string.Empty;//实际文件名称
    private string strFileName = string.Empty;//文件格式

    ManagerQuestion objQuestion = new ManagerQuestion();
    Course objCourse = new Course();
    string strTemp = "doc";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["UserID"] = 10000;
            BinderDLL();
            InitPage();

           
        }
    }

    protected override void InitPage()
    {
        lab_TitleInfo.Text = GetLanageValueByKey("lab_AddQuestionInfo_danx_AttributeTitle", PowerCreator.LMS.Language.LanagetItemType.Page);
        lab_Course.Text = GetLanageValueByKey("lab_AddQuestionInfo_danx_CourseName", PowerCreator.LMS.Language.LanagetItemType.Page);
        lab_QuestionState.Text = GetLanageValueByKey("lab_AddQuestionInfo_danx_QuestionState", PowerCreator.LMS.Language.LanagetItemType.Page);
        lab_QeustionDiffculty.Text = GetLanageValueByKey("lab_AddQuestionInfo_danx_QuestionDiffculty", PowerCreator.LMS.Language.LanagetItemType.Page);
        lab_Ken.Text = GetLanageValueByKey("lab_AddQuestionInfo_danx_Ken", PowerCreator.LMS.Language.LanagetItemType.Page);
        lab_DefaultScore.Text = GetLanageValueByKey("lab_AddQuestionInfo_danx_DefaultScore", PowerCreator.LMS.Language.LanagetItemType.Page);
        lab_SelectFile.Text = GetLanageValueByKey("lab_AddQuestionResourceMini_SelectFile", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Description_title.Text = GetLanageValueByKey("lbl_QuestionToIn_Description_title", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Description_1.Text = GetLanageValueByKey("lbl_QuestionToIn_Description_1", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Description_2.Text = GetLanageValueByKey("lbl_QuestionToIn_Description_2", PowerCreator.LMS.Language.LanagetItemType.Page);
        lab_Type.Text = GetLanageValueByKey("lab_QuestionToIn_QuestionInType", PowerCreator.LMS.Language.LanagetItemType.Page);

        btn_DownLoad.Text = GetLanageValueByKey("btn_QuestionToIn_DownFile", PowerCreator.LMS.Language.LanagetItemType.Page);
        btnSubmit.Text = GetLanageValueByKey("btn_QuestionToIn_DaoruQuestion", PowerCreator.LMS.Language.LanagetItemType.Page);

        base.InitPage();
    }

    //绑定课程列表
    private void BinderDLL()
    {
        ddlCourseList.DataSource = objCourse.Query("");
        ddlCourseList.DataTextField = "CourseName";
        ddlCourseList.DataValueField = "Course_Id";
        ddlCourseList.DataBind();
        ddlCourseList.Items[0].Text = GetLanageValueByKey("Msg_ManagerQuestion_PleaseCheck", PowerCreator.LMS.Language.LanagetItemType.Page);

        ddlQuestionState.Items[0].Text = GetLanageValueByKey("dpdlst_ManagerQuestion_UnUse", PowerCreator.LMS.Language.LanagetItemType.Page);
        ddlQuestionState.Items[1].Text = GetLanageValueByKey("dpdlst_ManagerQuestion_IsUse", PowerCreator.LMS.Language.LanagetItemType.Page);

    }

    //上传软件
    bool UploadFile()
    {
        if (File1.PostedFile.FileName.Length < 1)
        {
            Script.Alert(Page, "msg", GetLanageValueByKey("Msg_QuestionToIn_PleaseSelectFile", PowerCreator.LMS.Language.LanagetItemType.Page));
            return false;
        }
        string strName = this.File1.PostedFile.FileName.ToString();
        int nlength = strName.Length - strName.LastIndexOf("\\") - 1;
        string ImgName = strName.Substring(strName.LastIndexOf("\\") + 1, nlength);
         strTemp = "";
        //获取软件格式
        strFileName = strName.Substring(strName.LastIndexOf(".")).Replace(".", "");
        if (strFileName.ToLower()=="docx")
        {
            strTemp = "doc";
        }
        if (strFileName.ToLower() != ddlType.SelectedValue.ToLower() && strTemp.ToLower()!= ddlType.SelectedValue.ToLower())
        {
            return false;
        }
        strTemp = strFileName.ToLower();
        ExcelName_New = Guid.NewGuid() + "." + strFileName.ToLower();
        string sPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "QuestionDocument\\" + ExcelName_New;
        //string sPath = Server.MapPath(Utils.WebRoot + "\\QuestionDocument\\" + ExcelName_New + ".word"); +"QuestionDocument\\" + ExcelName_New;
        try
        {
            this.File1.PostedFile.SaveAs(sPath);
            return true;
        }
        catch
        {
            return false;
        }

    }
    private bool ToExcel()
    {
        UploadFile();
        return true;
    }

    private string ToText()
    {
        string msg = string.Empty;
        string strFile = "";

        try
        {
            
            //取得Word文件保存路径
            string  filePath = Server.MapPath(WebUtils.WebRoot + "\\QuestionDocument\\" + ExcelName_New);


            strFile = System.IO.File.ReadAllText(filePath,Encoding.Default);

            ArrayList objlist = new ArrayList();
            string[] str_QuestionCount = new string[1];
            str_QuestionCount[0] = "★★★";
            strFile = strFile.Replace("\n", "").Replace("\t", "").Replace("\r", "");

            if (strFile.IndexOf("★★★") == -1 | strFile.IndexOf("#") == -1 | strFile.IndexOf("『") == -1 | strFile.IndexOf("』") == -1)
            {
                //Script.Alert(Page, "msg", "没有符合格式的试题");
                //return false;
                msg = GetLanageValueByKey("Msg_QuestionToIn_NoQuestion", PowerCreator.LMS.Language.LanagetItemType.Page);
                return msg;
            }
            string[] strFileList = strFile.Split(str_QuestionCount, StringSplitOptions.RemoveEmptyEntries);

            int questionTypeIndex = 0;
            int questionindex = 0;
            string questionType = string.Empty;
            string question = string.Empty;
            int RightQuestionCount = 0;//成功导入题目的个数
            int WrongQuestionCount = 0;  //错误题目的总个数
            int SameQuestionCount = 0;//重复题目的总个数

            for (int i = 0; i < strFileList.Length; i++)
            {
                VOQuestion objQuestionInfo = new VOQuestion();

                ArrayList objQuestionOptionInfo_List = new ArrayList();

                string question_str = strFileList[i].ToString();
                questionTypeIndex = question_str.IndexOf('#', 0);
                questionType = question_str.Substring(0, questionTypeIndex).Replace("#", "");
                int questionType_int = ConvertQuestionType(questionType);
                question_str = question_str.Remove(0, questionTypeIndex + 1);
                questionindex = question_str.IndexOf("『", 0);
                question = question_str.Substring(0, questionindex).Replace("『", "");
                question_str = question_str.Remove(0, questionindex + 1).Replace("』", "");
                string questionParse = string.Empty;
                ArrayList rightAnswerList = new ArrayList();
                if (questionType_int < 4)//提取客观题答案
                {
                    string[] str_QuestionOptionCount = new string[1];
                    str_QuestionOptionCount[0] = "○";

                    string[] answerList = question_str.Trim().Split(str_QuestionOptionCount, StringSplitOptions.RemoveEmptyEntries);


                    for (int j = 0; j < answerList.Length; j++)
                    {
                        string str_Option = answerList[j].ToString();
                        string optionIndex = ConvertOptionID(j);
                        int rightAnswerCount = -1;
                        rightAnswerCount = str_Option.IndexOf("●");
                        if (rightAnswerCount == 0)
                        {
                            str_Option = answerList[j].Replace("●", "");
                            rightAnswerList.Add(optionIndex);
                        }
                        objQuestionOptionInfo_List.Add(optionIndex + "、" + str_Option.ToString());
                    }
                }
                else//提取主观题答案
                {
                    questionParse = question_str;
                }

                if (objQuestion.QueryQuestion(" FKQuestionTypeID=" + ConvertQuestionType(questionType) + " and FKQuestionCourseID=" + ddlCourseList.SelectedValue + " and QuestionContent='" + question.Replace("'", "''") + "'").Rows.Count > 0)
                {
                    SameQuestionCount += 1;
                    continue;
                }

                objQuestionInfo.QuestionContent = question;

                objQuestionInfo.FKQuestionTypeID = ConvertQuestionType(questionType);
                objQuestionInfo.QuestionDiffculty = int.Parse(ddlDiffculty.SelectedValue);
                objQuestionInfo.FKQuestionCourseID = int.Parse(ddlCourseList.SelectedValue);
                objQuestionInfo.QuestionKen = txtKen.Text;
                objQuestionInfo.QuestionIsFather = 0;
                if (objQuestionInfo.FKQuestionTypeID > 3)
                {
                    objQuestionInfo.QuestionClass = 1;// 主观题
                    objQuestionInfo.QuestionParse = questionParse;
                }
                else
                {
                    objQuestionInfo.QuestionParse = "";
                    objQuestionInfo.QuestionClass = 2;//客观题
                }
                objQuestionInfo.QuestionState = int.Parse(ddlQuestionState.SelectedValue);
                if (questionType_int == 4)
                {
                    question_str = question_str.Remove(0, 1);
                    objQuestionInfo.QuestionAnswer = question_str.Replace("○", "$");
                }
                else
                {
                    objQuestionInfo.QuestionAnswer = ConvertRightAnswer(rightAnswerList);
                }

                objQuestionInfo.QuestionDefaultScore = int.Parse(txtDefaultScore.Text);
                objQuestionInfo.QuestionCreateID = int.Parse(ViewState["UserID"].ToString());//int.Parse(Session["UserID"].ToString());
                objQuestionInfo.QuestionCreateTime = DateTime.Now;

                try
                {


                    objQuestion.CreateQuestionOptionList(objQuestionInfo, objQuestionOptionInfo_List);
                    RightQuestionCount += 1;
                }
                catch
                {
                    WrongQuestionCount += 1;
                }



            }

            msg = GetLanageValueByKey("Msg_QuestionToIn_QuestionSumCount", PowerCreator.LMS.Language.LanagetItemType.Page) + strFileList.Length.ToString() + "" + ";" + GetLanageValueByKey("Msg_QuestionToIn_QuestionOKCount", PowerCreator.LMS.Language.LanagetItemType.Page) + RightQuestionCount.ToString() + "" + ";" + GetLanageValueByKey("Msg_QuestionToIn_QuestionErorCount", PowerCreator.LMS.Language.LanagetItemType.Page) + WrongQuestionCount.ToString() + "" + ";" + GetLanageValueByKey("Msg_QuestionToIn_QuestionSameCount", PowerCreator.LMS.Language.LanagetItemType.Page) + SameQuestionCount.ToString();
            return msg;
        }
        catch (Exception ex)
        {
            msg = GetLanageValueByKey("Msg_QuestionToIn_QuestionInErorMsg", PowerCreator.LMS.Language.LanagetItemType.Page) + "：" + ex.Message;
            return msg;
        }
    }

    private string ToWord()
    {

        string msg = string.Empty;
        string strFile = "";
        
        try
        {
            Object Nothing = System.Reflection.Missing.Value;
            //取得Word文件保存路径
            object filename = Server.MapPath(WebUtils.WebRoot + "\\QuestionDocument\\" + ExcelName_New);
            //创建一个名为WordApp的组件对象
            Word.ApplicationClass WordApp = new Word.ApplicationClass();
            Word.Document doc = new Document();
            if (strTemp == "doc")
            {
                doc = WordApp.Documents.Open(

                ref filename, ref Nothing, ref Nothing,

                                      ref Nothing, ref Nothing, ref Nothing,

                                      ref Nothing, ref Nothing, ref Nothing,

                                      ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

                strFile = doc.Content.Text.ToString();
            }
            //else
            //{
            //    using( Package pc = Package.Open(filename.ToString()))
            //    {
                   
            //        Uri docxUri = new Uri("/word/document.xml",UriKind.Relative);
            //        PackagePart docxPart = pc.GetPart(docxUri);
            //        XmlDocument docxDocument = new XmlDocument ();
            //        docxDocument.Load(docxPart.GetStream());
            //        strFile=docxDocument.InnerText.ToString();
            //    } 
            //}
            doc.Close(ref Nothing, ref Nothing, ref Nothing);
            //关闭WordApp组件对象
            WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);


            ArrayList objlist = new ArrayList();
            string[] str_QuestionCount = new string[1];
            str_QuestionCount[0] = "★★★";
            strFile = strFile.Replace("\n", "").Replace("\t", "").Replace("\r", "");

            if (strFile.IndexOf("★★★") == -1 | strFile.IndexOf("#") == -1 | strFile.IndexOf("『") == -1 | strFile.IndexOf("』") == -1)
            {
                //Script.Alert(Page, "msg", "没有符合格式的试题");
                //return false;
                msg = GetLanageValueByKey("Msg_QuestionToIn_NoQuestion", PowerCreator.LMS.Language.LanagetItemType.Page);
                return msg;
            }
            string[] strFileList = strFile.Split(str_QuestionCount, StringSplitOptions.RemoveEmptyEntries);

            int questionTypeIndex = 0;
            int questionindex = 0;
            string questionType = string.Empty;
            string question = string.Empty;
            int RightQuestionCount = 0;//成功导入题目的个数
            int WrongQuestionCount = 0;  //错误题目的总个数
            int SameQuestionCount = 0;//重复题目的总个数

            for (int i = 0; i < strFileList.Length; i++)
            {
                VOQuestion objQuestionInfo = new VOQuestion();
                
                ArrayList objQuestionOptionInfo_List = new ArrayList();

                string question_str = strFileList[i].ToString();
                questionTypeIndex = question_str.IndexOf('#', 0);
                questionType = question_str.Substring(0, questionTypeIndex).Replace("#", "");
                int questionType_int = ConvertQuestionType(questionType);
                question_str = question_str.Remove(0, questionTypeIndex + 1);
                questionindex = question_str.IndexOf("『", 0);
                question = question_str.Substring(0, questionindex).Replace("『", "");
                question_str = question_str.Remove(0, questionindex + 1).Replace("』", "");
                string questionParse = string.Empty;
                ArrayList rightAnswerList = new ArrayList();
                if (questionType_int < 4)//提取客观题答案
                {
                    string[] str_QuestionOptionCount = new string[1];
                    str_QuestionOptionCount[0] = "○";

                    string[] answerList = question_str.Trim().Split(str_QuestionOptionCount, StringSplitOptions.RemoveEmptyEntries);


                    for (int j = 0; j < answerList.Length; j++)
                    {
                        string str_Option = answerList[j].ToString();
                        string optionIndex = ConvertOptionID(j);
                        int rightAnswerCount = -1;
                        rightAnswerCount = str_Option.IndexOf("●");
                        if (rightAnswerCount == 0)
                        {
                            str_Option = answerList[j].Replace("●", "");
                            rightAnswerList.Add(optionIndex);
                        }
                        objQuestionOptionInfo_List.Add(optionIndex + "、" + str_Option.ToString());
                    }
                }
                else//提取主观题答案
                {
                    questionParse = question_str;
                }

                if (objQuestion.QueryQuestion(" FKQuestionTypeID=" + ConvertQuestionType(questionType) + " and FKQuestionCourseID=" + ddlCourseList.SelectedValue + " and QuestionContent='" + question.Replace("'","''") + "'").Rows.Count > 0)
                {
                    SameQuestionCount += 1;
                    continue;
                }

                objQuestionInfo.QuestionContent = question;

                objQuestionInfo.FKQuestionTypeID = ConvertQuestionType(questionType);
                objQuestionInfo.QuestionDiffculty = int.Parse(ddlDiffculty.SelectedValue);
                objQuestionInfo.FKQuestionCourseID = int.Parse(ddlCourseList.SelectedValue);
                objQuestionInfo.QuestionKen = txtKen.Text;
                objQuestionInfo.QuestionIsFather = 0;
                if (objQuestionInfo.FKQuestionTypeID > 3)
                {
                    objQuestionInfo.QuestionClass = 1;// 主观题
                    objQuestionInfo.QuestionParse = questionParse;
                }
                else
                {
                    objQuestionInfo.QuestionParse = "";
                    objQuestionInfo.QuestionClass = 2;//客观题
                }
                objQuestionInfo.QuestionState = int.Parse(ddlQuestionState.SelectedValue);
                if (questionType_int == 4)
                {
                    question_str = question_str.Remove(0, 1);
                    objQuestionInfo.QuestionAnswer = question_str.Replace("○", "$");
                }
                else
                {
                    objQuestionInfo.QuestionAnswer = ConvertRightAnswer(rightAnswerList);
                }

                objQuestionInfo.QuestionDefaultScore = int.Parse(txtDefaultScore.Text);
                objQuestionInfo.QuestionCreateID = int.Parse(ViewState["UserID"].ToString());//int.Parse(Session["UserID"].ToString());
                objQuestionInfo.QuestionCreateTime = DateTime.Now;
               
                try
                {


                    objQuestion.CreateQuestionOptionList(objQuestionInfo, objQuestionOptionInfo_List);
                    RightQuestionCount += 1;
                }
                catch
                {
                    WrongQuestionCount += 1;
                }



            }

            msg = GetLanageValueByKey("Msg_QuestionToIn_QuestionSumCount", PowerCreator.LMS.Language.LanagetItemType.Page) + strFileList.Length.ToString() + "" + ";" + GetLanageValueByKey("Msg_QuestionToIn_QuestionOKCount", PowerCreator.LMS.Language.LanagetItemType.Page) + RightQuestionCount.ToString() + "" + ";" + GetLanageValueByKey("Msg_QuestionToIn_QuestionErorCount", PowerCreator.LMS.Language.LanagetItemType.Page) + WrongQuestionCount.ToString() + "" + ";" + GetLanageValueByKey("Msg_QuestionToIn_QuestionSameCount", PowerCreator.LMS.Language.LanagetItemType.Page) + SameQuestionCount.ToString();
            return msg;
        }
        catch (Exception ex)
        {
            msg = GetLanageValueByKey("Msg_QuestionToIn_QuestionInErorMsg", PowerCreator.LMS.Language.LanagetItemType.Page) + "：" + ex.Message;
            return msg;
        }
    }
   
    private string ConvertOptionID(int Index)
    {
        string OptionID = string.Empty;
        switch (Index)
        {
            case 0: OptionID = "A";
                break;
            case 1: OptionID = "B";
                break;
            case 2: OptionID = "C";
                break;
            case 3: OptionID = "D";
                break;
            case 4: OptionID = "E";
                break;
            case 5: OptionID = "F";
                break;
        }
        return OptionID;
    }
    private string ConvertRightAnswer(ArrayList rightAnswerList)
    {
        StringBuilder rightAnswer=new StringBuilder();
        //for (int i = 0; i < rightAnswerList.Count; i++)
        //{
        //    if (rightAnswerList[i].ToString() == "0")
        //    {
        //        rightAnswerList[i] = "A";
        //    }
        //    else if (rightAnswerList[i].ToString() =="1")
        //    {
        //        rightAnswerList[i] = "B";
        //    }
        //    else if (rightAnswerList[i].ToString() == "2")
        //    {
        //        rightAnswerList[i] = "C";
        //    }
        //    else if (rightAnswerList[i].ToString() == "3")
        //    {
        //        rightAnswerList[i] = "D";
        //    }
        //    else if (rightAnswerList[i].ToString() == "4")
        //    {
        //        rightAnswerList[i] = "E";
        //    }
        //    else
        //    {
        //        rightAnswerList[i] = "F";
        //    }
        //}
        for (int i = 0; i < rightAnswerList.Count; i++)
        {
            if (rightAnswer.Length > 0)
            {
                rightAnswer.Append( "$"+rightAnswerList[i].ToString() );
            }
            else
            {
                rightAnswer.Append(rightAnswerList[i].ToString());
            }
        }
        return rightAnswer.ToString();
    }
    private int ConvertQuestionType(string questionType)
    {
        int qType = 0;
        switch (questionType)
        {
            case"判断题":
                qType = 1;
                break;
            case "单选题":
                qType = 2;
                break;
            case "多选题":
                qType = 3;
                break;
            case "填空题":
                qType = 4;
                break;
            case "名词解释":
                qType = 5;
                break;
            case "简答题":
                qType = 6;
                break;
            case "组合题":
                qType = 7;
                break;
        }
        return qType;
    }
    private bool PageCheck()
    {
        if (string.IsNullOrEmpty(txtDefaultScore.Text.Trim()) | string.IsNullOrEmpty(txtKen.Text.Trim()))
        {
            Script.Alert(this, "msg", GetLanageValueByKey("Msg_QuestionToIn_checkmsg1", PowerCreator.LMS.Language.LanagetItemType.Page));
            return false;
        }
        if (!PageValidate.IsNumber(txtDefaultScore.Text.Trim()))
        {
            Script.Alert(this, "msg", GetLanageValueByKey("Msg_QuestionToIn_checkmsg2", PowerCreator.LMS.Language.LanagetItemType.Page));
            return false;
        }
        if (ddlCourseList.SelectedValue == "-1")
        {
            Script.Alert(this, "msg", GetLanageValueByKey("Msg_QuestionToIn_checkmsg3", PowerCreator.LMS.Language.LanagetItemType.Page));
            return false;
        }
        return true;
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        if (!PageCheck())
        {
            return;
        }
        if (!UploadFile())
        {
            Script.Alert(Page, "msg", GetLanageValueByKey("Msg_QuestionToIn_checkmsg4", PowerCreator.LMS.Language.LanagetItemType.Page));
            return;
        }
        string path = string.Empty;
        //if (rdbtn_Excel.Checked)
        //{
        //    path = Server.MapPath(Utils.WebRoot + "\\QuestionDocument\\" + ExcelName_New + ".xls");
        //    Script.Alert(Page, "msg", "请使用WORD");
            
        //}
        //else
        //{
            //path = Server.MapPath(WebUtils.WebRoot + "\\QuestionDocument\\" + ExcelName_New + ".word");
            lab_Msg.Visible = true;
            if (ddlType.SelectedValue.ToLower() == "doc" || ddlType.SelectedValue.ToLower() == "docx")
            {
                lab_Msg.Text = GetLanageValueByKey("Msg_QuestionToIn_checkmsg5", PowerCreator.LMS.Language.LanagetItemType.Page) + "：" + ToWord();
            }
            else
            {
                lab_Msg.Text = GetLanageValueByKey("Msg_QuestionToIn_checkmsg5", PowerCreator.LMS.Language.LanagetItemType.Page) + "：" + ToText();
            }
            //Script.Alert(Page, "msg", ToWord());


        //}
        //if (objexcel.ExcelData(path, "", "QuestionInfo"))
        //{
        //    Script.Alert(Page, "msg", "导入成功");
        //}
        //else
        //{
        //    Script.Alert(Page, "msg", "导入失败");
        //}


    }
    protected void btn_DownLoad_Click(object sender, EventArgs e)
    {
        Script.RedirectURL(WebUtils.WebRoot + "/QuestionDocument/AddQuestion_Demo.doc");
        
    }
}
